<?php

namespace Biz\tools\helper;

/**
 * 公用方法类
 *
 */

use Doraemon\tools\Log;
use Biz\model\wiki\Wiki;
use Doraemon\tools\Curl;
use Biz\model\brand\Brand;
use Biz\model\ShopFavorite;
use Biz\cache\wiki\GoodsHot;
use Doraemon\tools\HhzClient;
use Doraemon\pockets\config\IniConfig;
use Illuminate\Support\Facades\Validator;
use Doraemon\pockets\constInterface\AppType;
use Biz\cache\brand\BrandShowActivity;

class Common
{
    /**
     * 二维数组按指定字段排序
     *
     * @param $list
     * @param $field
     * @param string $sortby
     * @return array|bool
     */
    public static function sortArrayByField($list, $field, $sortby = 'asc')
    {
        if (is_array($list)) {
            $refer = $resultSet = [];
            foreach ($list as $i => $data) {
                $refer[$i] = &$data[$field];
            }
            switch ($sortby) {
                case 'asc': // 正向排序
                    asort($refer);
                    break;
                case 'desc': // 逆向排序
                    arsort($refer);
                    break;
                case 'nat': // 自然排序
                    natcasesort($refer);
                    break;
                default:
                    natcasesort($refer);
            }
            foreach ($refer as $key => $val) {
                $resultSet[] = &$list[$key];
            }
            return $resultSet;
        }
        return false;
    }

    /**
     * 请求
     * @param string $method GET/POST
     * @param array $params
     * @param string $log_title
     * @return array|mixed
     */
    public static function requestUrl($method = 'GET', $params = [], $url = '', $log_title = '请求异常日志')
    {
        $rs = [];
        try {
            if (!$url) {
                throw new \Exception("url为空");
            }
            if (strtolower($method) == 'get') {
                $str = '';
                foreach ($params as $key => $param) {
                    $str .= $key . "=" . $param . '&';
                }
                $str = rtrim($str, '&');
                $url .= "?" . $str;
                $params = [];
            }
            $result = Curl::Request($method, $url, $params);
            if ($result['code'] === 1) {
                $info = $result['json']['data'];
                $rs = $info['content_list'];
            }
        } catch (\Exception $e) {
            Log::error($log_title, [
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);
        }
        return $rs;
    }

    /**
     * 根据类型获取 url
     * @param $tabType //配置的url名称
     * @param $config_file //配置文件
     * @param $config_select //配置问价标题
     * @return mixed
     * @throws \Exception
     */
    public static function getUrl($tabType, $config_file, $config_select)
    {
        $config = IniConfig::getConfigSelect($config_file, $config_select);
        return $config[$tabType];
    }

    /**
     * 二维数组 根据字段进行键值整合
     * @param array $arr
     * @param $key
     * @return array
     */
    public static function keyBy(array $arr, $key): array
    {
        $data = [];
        if (!$arr) {
            return $data;
        }
        foreach ($arr as $item) {
            if (isset($item[$key]) && $item[$key]) {
                $data[$item[$key]][] = $item;
            }
        }
        return $data;
    }

    /**
     * 请求表单验证
     *
     * @param array $checkRule 验证规则
     * @param array $data 要验证的数据
     * @return int
     */
    public static function validatorRule(array $checkRule, array $data)
    {
        $messages = [
            'required' => '参数 :attribute是必须传递参数.',
            'max' => '参数 :attribute 不能大于 :max.',
            'integer' => '参数 :attribute是必须是整型',
            'numeric' => '参数 :attribute是必须是数字',
            'url' => '参数 :attribute是必须是连接',
            'json' => '参数 :attribute是必须是json',
            'date' => '参数 :attribute是必须是日期类型的',
            'in' => '参数 :attribute不是指定的范围内',
            'mimes' => '参数 :attribute不是指定的文件',
        ];
        $validator = Validator::make($data, $checkRule, $messages);

        if ($validator->fails()) {
            //获取错误的方法是 errors
            return $validator->errors()->first();//返回第一个
        }
        return true;
    }

    /**
     * 获取符合字段和字段值的数组集合
     * @param array $data 待过滤数组
     * @param string $field 要查找的字段
     * @param $value @要查找的字段值
     * @return array 返回所有符合要求的数组集合
     */
    public static function arrayFilterFieldValue(array $data, string $field, $value): array
    {
        return array_filter($data, static function ($row) use ($field, $value) {
            if (isset($row[$field])) {
                return $row[$field] == $value;
            }
        });
    }


    /**
     * 获取随机用户头像
     * @param int $num
     * @return array
     */
    public static function getRandAvatars(int $num = 3): array
    {
        //获取机器人 uid集合
        $uids = self::getMechanicUids();
//        $uids = [11910,11912,19626076];
        //获取机器人
        $rand_uids = [];
        $rand_uid_keys = array_rand($uids, $num);
        foreach ($rand_uid_keys as $key) {
            $rand_uids[] = $uids[$key];
        }
        //获取用户信息
        $memberList = \Doraemon\service\User::getBatchBasicUserInfo($rand_uids);
        return array_column($memberList, 'small_avatar');
    }




    /**
     * 按照wiki热度排序 (必须存在Basic_id)
     * @param array $list
     * @return array
     */
    public static function sortByHot(array $list): array
    {
        $basic_ids = array_column($list, 'basic_id');
        if (!$basic_ids) {
            return $list;
        }
        $cache_hots = GoodsHot::getMulti($basic_ids);
        $cache_ids = array_keys($cache_hots);
        foreach ($list as $k => $item) {
            if (in_array($item['basic_id'], $cache_ids)) {
                $list[$k]['hot'] = $cache_hots[$item['basic_id']] ?? 0;
            }
        }
        //取热度
        $hots = array_column($list, 'hot');
        //按照热度排序hots
        array_multisort($hots, SORT_DESC, $list);
        return $list;
    }

    /**
     * 按照wiki热度排序 (必须存在Basic_id)
     * @param array $basicIds
     * @return array
     */
    public static function sortWikiIdsByHot(array $basicIds): array
    {
        $cacheHots = GoodsHot::getMulti($basicIds);
        //调试数据  需要打开注释即可
//        foreach ($cacheHots as &$cacheHot) {
//            $cacheHot = random_int(1, 100000);
//        }
        $list = [];
        foreach ($basicIds as $basicId) {
            if (array_key_exists($basicId, $cacheHots)) {
                $list[$basicId]['hot'] = $cacheHots[$basicId] ?? 0;
                $list[$basicId]['basic_id'] = $basicId;
            }
        }

        //取热度
        $hots = array_column($list, 'hot');
        //按照热度排序hots
        array_multisort($hots, SORT_DESC, $list);

        return array_column($list, 'basic_id');
    }


    /**
     * 获取是否收藏 列表必须包含wiki_id
     * @param $uid
     * @param array $list
     * @return array
     * @throws \Exception
     */
    public static function isFav($uid, array $list): array
    {
        $appSource = 0;
        if (HhzClient::getClientType() == AppType::APPTYPE_PARAGRAPH_MINIPROGRAM) {
            $appSource = AppType::APPTYPE_PARAGRAPH_MINIPROGRAM;
        } elseif (HhzClient::getClientType() == AppType::APPTYPE_DESIGNER_FUNENG_MINIPROGRAM) {
            $appSource = AppType::APPTYPE_DESIGNER_FUNENG_MINIPROGRAM;
        }
        $wiki_ids = array_column($list, 'wiki_id');
        $isFavList = $wiki_ids ? ShopFavorite::is_favorited($uid, $wiki_ids, ShopFavorite::TYPE_WIKI,
            $appSource) : [];
        foreach ($list as $k => $v) {
            $list[$k]['is_fav'] = $isFavList[$v['wiki_id']] ?? 0;
        }
        return $list;
    }

    /**
     * 过滤失效wiki 返回有效wiki列表
     * @param array $list
     * @return array
     */
    public static function getWikiList(array $list): array
    {
        $newList = [];
        if (!$list) {
            return $newList;
        }
        foreach ($list as $item) {
            if ($item['channel_spu_status'] != Wiki::CHANNEL_SPU_STATUS_OFF) {
                $newList[] = $item;
            }
        }
        return $newList;
    }


    /**
     * app格式化连接（非全屏）
     * @param $url
     * @return string
     * @throws \JsonException
     */
    public static function formatLinkNormalLink($url): string
    {
        return 'niceliving://webview/normalscreen?protego=' . urlencode(base64_encode(json_encode(['url' => $url],
                JSON_THROW_ON_ERROR)));
    }

    /**
     * app格式化连接（全屏）
     * @param $url
     * @return string
     * @throws \JsonException
     */
    public static function formatFullScreenLink($url): string
    {
        return 'niceliving://webview/fullscreen?protego=' . urlencode(base64_encode(json_encode(['url' => $url],
                JSON_THROW_ON_ERROR)));
    }

    /**
     * 5秒提交锁定
     * @param $key
     * @return void
     * @throws \Exception
     */
    public static function lockTimes($key)
    {
        $isset = BrandShowActivity::isLock($key, 5);
        if ($isset) {
            throw new \Exception("请勿重复提交");
        }
    }


    /**
     * 友好显示var_dump.
     *
     * @param mixed      $var
     * @param mixed      $echo
     * @param null|mixed $label
     * @param mixed      $strict
     */
    public static function dump($var, $echo = true, $label = null, $strict = true)
    {
        $label = ($label === null) ? '' : rtrim($label) . ' ';
        if (!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            } else {
                $output = $label . print_r($var, true);
            }
        } else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if (!extension_loaded('xdebug')) {
                $output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            }
        }
        if ($echo) {
            echo $output; die;
        }

        return $output;
    }

    /**
     * 打印函数
     * $arr 需要输出的数组.
     *
     * @param mixed $arr
     */
    public static function p($arr): void
    {
        echo '<pre>';
        print_r($arr);
        echo '</pre>';
    }


    /**
     * 获取好好住内部员工账号（8月份）
     * @return int[]
     */
    public static function getHhzWorkerUids(): array
    {
        return [
            11904,
            11903,
            11906,
            147218,
            11908,
            12165175,
            1274874,
            391369,
            11933,
            1325024,
            1678570,
            8205180,
            6879499,
            11058950,
            5505218,
            5014342,
            3928360,
            11350658,
            2499639,
            4123407,
            2055794,
            12120114,
            10964163,
            5342376,
            1549444,
            65488,
            6135623,
            272095,
            565573,
            12122269,
            6361403,
            1937722,
            11896131,
            11134265,
            11218845,
            8254369,
            6510522,
            282732,
            3274553,
            9627677,
            12487788,
            12414200,
            47572,
            8809891,
            12065349,
            6313102,
            6241772,
            9470904,
            743671,
            11631494,
            10970206,
            11907,
            3199478,
            12113971,
            12317429,
            8596807,
            10486758,
            3589600,
            9412678,
            10493398,
            12015,
            587271,
            86775,
            20416,
            6086284,
            4715572,
            2212496,
            6999627,
            11434729,
            1850457,
            1057516,
            1114058,
            6846376,
            3427148,
            9286263,
            2229658,
            7817748,
            7360089,
            9487344,
            3645622,
            11592378,
            11372470,
            12397359,
            11133143,
            10746180,
            3477816,
            11747973,
            12107160,
            10943772,
            11479553,
            562024,
            89512,
            10173406,
            11434382,
            6932921,
            10602765,
            12324390,
            12156268,
            12091797,
            12243245,
            10953609,
            6939276,
            10511572,
            7996057,
            5576791,
            3848739,
            11550064,
            4740312,
            231556,
            11413271,
            879787,
            9971151,
            3482276,
            3345683,
            11741166,
            10884453,
            2537919,
            10512499,
            578155,
            2899383,
            11957487,
            10415541,
            11914,
            1703208,
            4522223,
            11813329,
            12049942,
            3651479,
            10199960,
            10102185,
            741878,
            2723725,
            20424,
            1346913,
            2502115,
            5358410,
            199905,
            4217263,
            37818,
            12047498,
            2360618,
            11902,
            5344083,
            11945883,
            12201598,
            3851968,
            2815687,
            12455340,
            319814,
            4843514,
            11403942,
            6941169,
            50720,
            11958,
            3522909,
            1823587,
            11965,
            193807,
            6789603,
            2500141,
            5608575,
            10263342,
            11355389,
            1852530,
            7411557,
            12179751,
            11788783,
            127485,
            11219104,
            12041706,
            5204625,
            55010,
            12489409,
            11050282,
            12406748,
            1680121,
            10536652,
            2394601,
            11937497,
            12481072,
            8360236,
            5581091,
            6615050,
            6321458,
            5471723,
            8427009,
            11991070,
            10493741,
            11181120,
            12235619,
            3192940,
            11073544,
            3645513,
            7328528,
            2305437,
            8688755,
            11117457,
        ];
    }

    /**
     * 获取员工uid集合
     * @return array
     */
    public static function getStaffUids(): array
    {
        //员工账户
        $worker_uids = self::getHhzWorkerUids();
        //官方账号
        $official_uids = [
            12694030,
            12456042,
            11088740,
            10970206,
            10188660,
            9708399,
            7471384,
            7323891,
            7200139,
            6587838,
            6254362,
            6084737,
            5251037,
            5068780,
            5040534,
            4684158,
            3913396,
            1193321,
            378994,
            11941,
            10001
        ];
        //过期品牌
        $brand_uids = Brand::getOverBrandsUids();

        return array_merge($brand_uids, $official_uids, $worker_uids) ?? [];

    }


    /**
     * 获取 机器人uid集合
     * @return int[]
     */
    public static function getMechanicUids(): array
    {
        return [
            7544576,
            7545088,
            7541249,
            7541505,
            7541761,
            7542017,
            7542529,
            7542785,
            7543041,
            7543297,
            7543553,
            7542469,
            7544065,
            7544321,
            7541510,
            7541766,
            7542022,
            7542534,
            7542790,
            7543046,
            7543302,
            7543558,
            7544070,
            7544326,
            7544582,
            7541255,
            7541767,
            7542023,
            7542791,
            7543303,
            7543559,
            7544071,
            7544327,
            7544583,
            7544839,
            7541256,
            7541512,
            7541768,
            7542024,
            7542536,
            7542792,
            7543304,
            7543560,
            7544072,
            7544328,
            7544584,
            7544840,
            7545096,
            7541257,
            7541513,
            7541769,
            7542025,
            7542537,
            7542793,
            7543049,
            7543305,
            7543561,
            7544329,
            7544585,
            7545097,
            7541258,
            7541514,
            7542026,
            7542538,
            7542794,
            7543050,
            7543306,
            7543562,
            7544074,
            7544330,
            7544586,
            7544842,
            7545098,
            7541515,
            7541771,
            7542027,
            7542539,
            7542795,
            7543051,
            7543307,
            7543563,
            7544075,
            7544331,
            7544587,
            7544843,
            7545099,
            7541260,
            7541516,
            7541772,
            7542028,
            7542540,
            7542796,
            7543052,
            7543308,
            7543564,
            7544076,
            7544588,
            7545100,
            7541261,
            7541517,
            7541773,
            7542541,
            7542797,
            7543053,
            7543309,
            7543565,
            7544077,
            7544234,
            7544490,
            7544746,
            7545002,
            7541419,
            7541675,
            7541931,
            7542443,
            7542955,
            7543467,
            7543979,
            7544235,
            7544491,
            7544747,
            7541420,
            7541676,
            7542444,
            7542700,
            7542956,
            7543212,
            7543468,
            7543980,
            7544236,
            7544492,
            7545004,
            7541421,
            7541677,
            7541933,
            7542445,
            7542957,
            7543213,
            7543469,
            7543981,
            7544237,
            7544749,
            7541678,
            7541934,
            7542446,
            7542702,
            7542958,
            7543214,
            7543470,
            7544238,
            7544494,
            7541423,
            7541679,
            7541935,
            7542447,
            7542959,
            7543215,
            7543471,
            7543983,
            7544239,
            7544495,
            7544751,
            7545007,
            7541424,
            7541680,
            7541936,
            7542448,
            7542704,
            7542960,
            7543216,
            7543472,
            7543984,
            7544240,
            7544496,
            7544752,
            7545008,
            7541425,
            7541681,
            7541937,
            7542449,
            7542961,
            7543217,
            7543473,
            7544241,
            7545009,
            7541682,
            7541938,
            7542450,
            7542962,
            7543218,
            7543474,
            7543986,
            7544498,
            7544754,
            7545010,
            7541427,
            7541683,
            7541939,
            7542451,
            7542707,
            7542963,
            7543219,
            7543475,
            7543987,
            7544243,
            7544499,
            7544755,
            7541428,
            7541684,
            7541940,
            7542452,
            7542708,
            7542964,
            7543220,
            7543476,
            7543988,
            7544500,
            7544756,
            7545012,
            7541429,
            7541941,
            7542453,
            7542709,
            7543221,
            7543477,
            7543989,
            7544245,
            7544501,
            7544757,
            7545013,
            7541686,
            7541942,
            7542454,
            7542710,
            7543222,
            7543478,
            7543990,
            7544246,
            7544502,
            7544758,
            7545014,
            7541431,
            7541687,
            7541943,
            7542455,
            7542711,
            7542967,
            7543223,
            7543479,
            7543991,
            7544247,
            7544503,
            7544759,
            7545015,
            7541432,
            7541688,
            7541944,
            7542456,
            7542968,
            7543224,
            7543480,
            7543992,
            7544248,
            7544504,
            7544760,
            7545016,
            7541433,
            7541689,
            7541945,
            7542457,
            7542969,
            7543225,
            7543481,
            7543993,
            7544505,
            7544761,
            7545017,
            7541434,
            7541690,
            7541946,
            7542458,
            7542714,
            7543226,
            7543482,
            7543994,
            7544250,
            7544506,
            7544762,
            7545018,
            7541435,
            7541691,
            7542459,
            7542715,
            7542971,
            7543227,
            7543483,
            7544251,
            7544507,
            7545019,
            7541436,
            7541692,
            7541948,
            7542460,
            7542716,
            7542972,
            7543228,
            7543996,
            7544252,
            7544508,
            7544764,
            7545020,
            7541437,
            7541693,
            7542461,
            7542717,
            7542973,
            7544253,
            7544509,
            7544765,
            7545021,
            7541438,
            7541694,
            7541950,
            7542974,
            7543230,
            7543486,
            7543998,
            7544766,
            7541439,
            7541695,
            7541951,
            7542463,
            7542719,
            7543231,
            7543487,
            7544255,
            7544511,
            7544767,
            7545023,
            7541440,
            7541696,
            7541952,
            7542464,
            7542976,
            7543232,
            7543488,
            7544000,
            7544256,
            7544512,
            7544768,
            7545024,
            7541441,
            7541697,
            7541953,
            7542465,
            7542721,
            7542977,
            7543233,
            7543489,
            7544001,
            7544257,
            7544513,
            7544769,
            7541442,
            7541698,
            7541954,
            7542466,
            7542722,
            7542978,
            7543234,
            7543490,
            7544258,
            7544514,
            7544770,
            7545026,
            7541699,
            7541955,
            7543235,
            7543491,
            7544003,
            7544259,
            7544515,
            7544771,
            7545027,
            7541444,
            7541700,
            7541956,
            7542468,
            7542724,
            7542980,
            7543236,
            7543492,
            7544004,
            7544260,
            7544516,
            7545028,
            7541445,
            7541701,
            7544832
        ];
    }
}
